const express = require('express');
const winston = require('winston');
const cors = require('cors');

// 初始化Express
const app = express();
const port = process.env.PORT || 3000;

// 配置CORS
app.use(cors());
// 解析JSON请求体
app.use(express.json());

// 配置winston日志
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
    new winston.transports.File({ filename: 'logs/combined.log' })
  ]
});

// 订单提交接口
app.post('/api/submit-order', (req, res) => {
  const orderData = req.body;
  // 记录订单日志
  logger.info('收到新订单', { order: orderData });
  // 模拟佣金计算（实际应与业务逻辑同步）
  const commission = (orderData.amount * 0.03).toFixed(2);
  res.json({
    code: 200,
    message: '订单提交成功',
    data: { commission }
  });
});

// 小程序更新接口（示例）
app.get('/api/check-update', (req, res) => {
  logger.info('检查小程序更新请求', { ip: req.ip });
  res.json({
    hasUpdate: false,
    version: '1.0.0',
    updateUrl: ''
  });
});

// 启动服务
app.listen(port, () => {
  logger.info(`服务端启动成功，端口：${port}`);
  console.log(`Server running on port ${port}`);
});